package org.joshsacks.fishies.ui.gl;

import javax.microedition.khronos.opengles.GL10;

import org.joshsacks.fishies.FishiesController;
import org.joshsacks.fishies.GameBoard.MatchSet;
import org.joshsacks.fishies.GameBoard.MatchSet.Match;
import org.joshsacks.fishies.Score;

import android.content.Context;
import android.graphics.PointF;

/**
 * Renders the a set of matches, blinking the transparency on the items.
 */
public class ScoreRenderer {
  private static long SCORE_FADE_IN_TIME = 650;
  private final Score score;
  private final PointF surfaceSize;
  private final FontManager fontManager;
  private RenderedText scoreText;
  private RenderedText scoreNumber;
  private RenderedText oldScoreNumber;
  long newScoreStart;
  int oldScore = -999;
  private static final int V_SPACING = 3;
  private int SCORE_HEIGHT = 32;
  public ScoreRenderer(FishiesController controller, 
          TextureManager textureManager, FontManager fontManager,
          PointF surfaceSize, GL10 gl) {
    this.score = controller.getScore();
    this.surfaceSize = surfaceSize;
    this.fontManager = fontManager;
    scoreText = new BitmapRenderedText(gl, "Score:", 32);
    updateScore(gl);
  }
    
  private void updateScore(GL10 gl) {
    if (score.getScore() == oldScore) {
      return;
    }
    oldScore = score.getScore();
    if (scoreNumber != null) {
      if (oldScoreNumber != null) {
        oldScoreNumber.discard(gl);
      }
      oldScoreNumber = scoreNumber;
      newScoreStart = System.currentTimeMillis();
    }
    scoreNumber = new BitmapRenderedText(gl, "" + score.getScore(), 32);      
  }

  public void render(Context context, GL10 gl) {
    updateScore(gl);
    gl.glDisable(GL10.GL_TEXTURE_2D);
    SquareRenderer square = new SquareRenderer(gl);
    square.addRectangle(0, 0, (int) surfaceSize.x,
            SCORE_HEIGHT + 4, null);
    gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    square.draw();

    square = new SquareRenderer(gl);
    square.addRectangle(2, 2, (int) surfaceSize.x - 4,
            SCORE_HEIGHT, null);
    gl.glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
    square.draw();
    gl.glEnable(GL10.GL_TEXTURE_2D);

    gl.glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    float width = scoreText.draw(gl, 4, V_SPACING); 
    long sinceFadeIn = System.currentTimeMillis() - newScoreStart;
    if (sinceFadeIn < SCORE_FADE_IN_TIME) {
      float alpha = sinceFadeIn / (float) SCORE_FADE_IN_TIME;
      gl.glColor4f(1.0f, 1.0f - alpha / 2, 0.6f - alpha / 2, 1 - alpha);
      oldScoreNumber.draw(gl, 4 + width, V_SPACING);     
      gl.glColor4f(1.0f, 1.0f, 0.6f, alpha);
      scoreNumber.draw(gl, 4 + width, V_SPACING);     
    } else {
      gl.glColor4f(1.0f, 1.0f, 0.6f, 1.0f);
      scoreNumber.draw(gl, 4 + width, V_SPACING + 1);      
    }
  }

  public int getHeight() {
    // TODO Auto-generated method stub
    return SCORE_HEIGHT + V_SPACING * 2;
  } 
}
